<template>
  <div class="page-container">
    <div class="page-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
        <el-breadcrumb-item to="/administrative">行政公文</el-breadcrumb-item>
        <el-breadcrumb-item>命令</el-breadcrumb-item>
      </el-breadcrumb>
      
      <div class="header-title">
        <h1>
          <el-icon class="title-icon"><Flag /></el-icon>
          命令生成
        </h1>
        <p class="subtitle">专业的命令生成工具，严谨格式，权威发布</p>
      </div>
      
      <!-- 进度指示器 -->
      <div class="steps-container">
        <el-steps :active="currentStep" align-center>
          <el-step title="基础信息" icon="EditPen" />
          <el-step title="更多信息" icon="InfoFilled" />
          <el-step title="生成命令" icon="DocumentChecked" />
        </el-steps>
      </div>
    </div>

    <!-- 步骤内容 -->
    <div class="step-content">
      <!-- 步骤1: 基础信息 -->
      <div v-show="currentStep === 0" class="step-panel">
        <el-card class="step-card">
          <template #header>
            <div class="card-header">
              <el-icon><EditPen /></el-icon>
              <span>基础信息</span>
            </div>
          </template>
          
          <el-form 
            :model="formData" 
            :rules="basicRules" 
            ref="basicFormRef" 
            label-width="120px"
            class="step-form"
          >
            <!-- 命令类型 -->
            <el-form-item label="命令类型" prop="commandType" required>
              <div class="radio-grid">
                <el-radio-group v-model="formData.commandType">
                  <el-radio value="administrative" class="radio-card">
                    <div class="radio-content">
                      <div class="radio-title">行政命令</div>
                      <div class="radio-desc">日常行政管理</div>
                    </div>
                  </el-radio>
                  <el-radio value="personnel" class="radio-card">
                    <div class="radio-content">
                      <div class="radio-title">人事任免</div>
                      <div class="radio-desc">人事调动任免</div>
                    </div>
                  </el-radio>
                  <el-radio value="emergency" class="radio-card">
                    <div class="radio-content">
                      <div class="radio-title">紧急动员</div>
                      <div class="radio-desc">紧急情况处置</div>
                    </div>
                  </el-radio>
                  <el-radio value="reward" class="radio-card">
                    <div class="radio-content">
                      <div class="radio-title">嘉奖令</div>
                      <div class="radio-desc">表彰奖励事项</div>
                    </div>
                  </el-radio>
                  <el-radio value="punishment" class="radio-card">
                    <div class="radio-content">
                      <div class="radio-title">惩处令</div>
                      <div class="radio-desc">纪律处分决定</div>
                    </div>
                  </el-radio>
                </el-radio-group>
              </div>
            </el-form-item>

            <!-- 主题 -->
            <el-form-item label="主题" prop="theme" required>
              <el-input
                v-model="formData.theme"
                placeholder="请输入主题"
                maxlength="200"
                show-word-limit
                class="theme-input"
              />
            </el-form-item>

            <!-- 内容物质 -->
            <el-form-item label="内容物质" prop="content" required>
              <el-input
                v-model="formData.content"
                type="textarea"
                :rows="6"
                placeholder="请输入内容物质"
                maxlength="3000"
                show-word-limit
                class="content-textarea"
              />
            </el-form-item>

            <!-- 篇幅 -->
            <el-form-item label="篇幅" prop="wordCount" required>
              <div class="word-count-container">
                <el-radio-group v-model="formData.wordCount" class="word-count-group">
                  <el-radio value="300">300字左右</el-radio>
                  <el-radio value="600">600字左右</el-radio>
                  <el-radio value="custom">自定义</el-radio>
                </el-radio-group>
                <el-input-number
                  v-if="formData.wordCount === 'custom'"
                  v-model="formData.customWordCount"
                  :min="200"
                  :max="2000"
                  :step="50"
                  placeholder="请输入字数"
                  class="custom-word-input"
                />
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- 步骤2: 更多信息 -->
      <div v-show="currentStep === 1" class="step-panel">
        <el-card class="step-card">
          <template #header>
            <div class="card-header">
              <el-icon><InfoFilled /></el-icon>
              <span>更多信息</span>
            </div>
          </template>
          
          <el-form 
            :model="formData" 
            :rules="advancedRules" 
            ref="advancedFormRef" 
            label-width="140px"
            class="step-form"
          >
            <!-- 主送/执行单位 -->
            <el-form-item label="主送/执行单位" prop="targetUnit" required>
              <el-input
                v-model="formData.targetUnit"
                placeholder="请输入主送/执行单位"
                maxlength="200"
                show-word-limit
                class="target-unit-input"
              />
            </el-form-item>

            <!-- 其他写作信息/要求 -->
            <el-form-item label="其他写作信息/要求">
              <el-input
                v-model="formData.otherInfo"
                type="textarea"
                :rows="4"
                placeholder="请输入其他写作信息"
                maxlength="3000"
                show-word-limit
                class="other-info-textarea"
              />
            </el-form-item>

            <!-- 参考文档 -->
            <el-form-item label="参考文档">
              <el-upload
                ref="uploadRef"
                v-model:file-list="formData.referenceFiles"
                class="upload-demo"
                drag
                :auto-upload="false"
                :multiple="false"
                :limit="1"
                accept=".doc,.docx,.xls,.xlsx"
                :before-upload="beforeUpload"
                :on-change="handleFileChange"
                :on-remove="handleFileRemove"
              >
                <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
                <div class="el-upload__text">
                  拖拽文件到此处或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    支持word、excel，文件2mb以内，最多一个文件
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- 步骤3: 生成结果 -->
      <div v-show="currentStep === 2" class="step-panel">
        <el-card class="step-card result-card">
          <template #header>
            <div class="card-header">
              <el-icon><DocumentChecked /></el-icon>
              <span>生成结果</span>
              <div class="header-actions">
                <el-button 
                  type="primary" 
                  :icon="RefreshRight" 
                  @click="generateContent" 
                  :loading="isGenerating"
                  size="small"
                >
                  {{ isGenerating ? '生成中' : '重新生成' }}
                </el-button>
              </div>
            </div>
          </template>
          
          <div v-if="!generatedContent && !isGenerating" class="generate-prompt">
            <el-empty description="点击下方按钮开始生成命令">
              <el-button type="primary" @click="generateContent" :icon="DocumentChecked">
                开始生成
              </el-button>
            </el-empty>
          </div>
          
          <div v-if="isGenerating" class="generating-state">
            <el-skeleton :rows="8" animated />
            <div class="generating-text">
              <el-icon class="rotating"><Loading /></el-icon>
              正在生成命令，请稍候...
            </div>
          </div>
          
          <div v-if="generatedContent" class="result-content">
            <div class="result-header">
              <h3>生成的命令内容</h3>
              <div class="result-actions">
                <el-button :icon="CopyDocument" @click="copyContent">
                  复制内容
                </el-button>
                <el-button :icon="Download" @click="exportContent">
                  导出文档
                </el-button>
              </div>
            </div>
            
            <div class="generated-text" v-html="formatContent(generatedContent)"></div>
            
            <div class="generation-info" v-if="generationStats">
              <el-divider />
              <div class="stats-grid">
                <div class="stat-item">
                  <span class="stat-label">字数：</span>
                  <span class="stat-value">{{ generationStats.wordCount }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">生成时间：</span>
                  <span class="stat-value">{{ generationStats.duration }}ms</span>
                </div>
                <div class="stat-item" v-if="generationStats.cost">
                  <span class="stat-label">消耗成本：</span>
                  <span class="stat-value">¥{{ generationStats.cost.toFixed(4) }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="step-actions">
      <el-button 
        v-if="currentStep > 0" 
        @click="prevStep" 
        :icon="ArrowLeft"
        size="large"
      >
        上一步
      </el-button>
      
      <el-button 
        v-if="currentStep < 2" 
        type="primary" 
        @click="nextStep" 
        :icon="ArrowRight"
        size="large"
      >
        下一步
      </el-button>
      
      <el-button 
        v-if="currentStep === 2 && !generatedContent" 
        type="primary" 
        @click="generateContent" 
        :loading="isGenerating"
        :icon="DocumentChecked"
        size="large"
      >
        {{ isGenerating ? '生成中...' : '生成命令' }}
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules, UploadFile, UploadProps } from 'element-plus'
import { 
  Flag, EditPen, InfoFilled, DocumentChecked, 
  ArrowLeft, ArrowRight, Loading, 
  CopyDocument, Download, RefreshRight, UploadFilled 
} from '@element-plus/icons-vue'
import { useModelConfigStore } from '@/stores/modelConfig'
import { aiService } from '@/services/aiService'
import type { ChatResponse } from '@/services/aiService'

interface CommandForm {
  // 基础信息
  commandType: string
  theme: string
  content: string
  wordCount: string
  customWordCount?: number
  
  // 更多信息
  targetUnit: string
  otherInfo: string
  referenceFiles: UploadFile[]
}

interface GenerationStats {
  wordCount: number
  duration: number
  cost?: number
}

// 表单数据
const formData = reactive<CommandForm>({
  commandType: '',
  theme: '',
  content: '',
  wordCount: '600',
  customWordCount: 600,
  targetUnit: '',
  otherInfo: '',
  referenceFiles: []
})

// 步骤管理
const currentStep = ref(0)

// 表单引用
const basicFormRef = ref<FormInstance>()
const advancedFormRef = ref<FormInstance>()
const uploadRef = ref()

// 生成状态
const isGenerating = ref(false)
const generatedContent = ref('')
const generationStats = ref<GenerationStats | null>(null)

// 表单验证规则
const basicRules: FormRules = {
  commandType: [
    { required: true, message: '请选择命令类型', trigger: 'change' }
  ],
  theme: [
    { required: true, message: '请输入主题', trigger: 'blur' },
    { min: 2, max: 200, message: '主题长度在 2 到 200 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容物质', trigger: 'blur' },
    { min: 10, max: 3000, message: '内容长度在 10 到 3000 个字符', trigger: 'blur' }
  ],
  wordCount: [
    { required: true, message: '请选择篇幅', trigger: 'change' }
  ]
}

const advancedRules: FormRules = {
  targetUnit: [
    { required: true, message: '请输入主送/执行单位', trigger: 'blur' },
    { min: 2, max: 200, message: '主送/执行单位长度在 2 到 200 个字符', trigger: 'blur' }
  ]
}

// 计算最终字数
const finalWordCount = computed(() => {
  return formData.wordCount === 'custom' ? formData.customWordCount : parseInt(formData.wordCount)
})

// 步骤操作
const nextStep = async () => {
  if (currentStep.value === 0) {
    if (!basicFormRef.value) return
    const valid = await basicFormRef.value.validate()
    if (!valid) return
  }
  
  if (currentStep.value === 1) {
    if (!advancedFormRef.value) return
    const valid = await advancedFormRef.value.validate()
    if (!valid) return
  }
  
  if (currentStep.value < 2) {
    currentStep.value++
  }
}

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

// 文件上传处理
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isValidType = ['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 
                      'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
                     .includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isValidType) {
    ElMessage.error('只能上传 Word 或 Excel 文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传文件大小不能超过 2MB!')
    return false
  }
  return false // 阻止自动上传
}

const handleFileChange = (_file: UploadFile) => {
  // 文件变更处理
}

const handleFileRemove = () => {
  formData.referenceFiles = []
}

// 生成命令内容
const generateContent = async () => {
  const modelStore = useModelConfigStore()
  const currentProvider = modelStore.getCurrentProvider()
  
  if (!currentProvider || !currentProvider.hasApiKey) {
    ElMessage.warning('请先配置AI模型的API密钥')
    return
  }
  
  isGenerating.value = true
  generatedContent.value = ''
  generationStats.value = null
  
  try {
    const commandTypeMap = {
      'administrative': '行政命令',
      'personnel': '人事任免', 
      'emergency': '紧急动员',
      'reward': '嘉奖令',
      'punishment': '惩处令'
    }
    
    const systemPrompt = `你是一个专业的公文写作助手，专门负责生成规范的命令。请根据用户提供的信息，生成一份专业、权威的命令。

命令写作要求：
1. 格式规范，符合公文标准和命令特点
2. 语言严谨、权威，具有强制性
3. 逻辑清晰，条理分明
4. 内容准确，指令明确
5. 体现命令的权威性和执行性
6. 字数控制在指定范围内

请生成完整的命令内容，包括标题、正文、执行要求等必要部分。命令应体现出权威性和强制执行力。`
    
    const userPrompt = `请根据以下信息生成命令：

命令类型：${commandTypeMap[formData.commandType as keyof typeof commandTypeMap] || formData.commandType}
主题：${formData.theme}
内容物质：${formData.content}
主送/执行单位：${formData.targetUnit}
字数要求：${finalWordCount.value}字左右

${formData.otherInfo ? `其他要求：${formData.otherInfo}` : ''}

请生成专业、权威的命令内容，体现命令的严肃性和执行力。`
    
    const response: ChatResponse = await aiService.generateText({
      systemPrompt,
      userPrompt
    })
    
    generatedContent.value = response.content
    generationStats.value = {
      wordCount: response.content.length,
      duration: response.duration,
      cost: response.cost
    }
    
    ElMessage.success('命令生成完成！')
  } catch (error) {
    console.error('生成命令失败:', error)
    ElMessage.error(`生成失败: ${error instanceof Error ? error.message : String(error)}`)
  } finally {
    isGenerating.value = false
  }
}

// 复制内容
const copyContent = async () => {
  try {
    await navigator.clipboard.writeText(generatedContent.value)
    ElMessage.success('内容已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败，请手动复制')
  }
}

// 导出内容
const exportContent = () => {
  const blob = new Blob([generatedContent.value], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `${formData.theme || '命令'}.txt`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
  ElMessage.success('导出成功')
}

// 格式化内容显示
const formatContent = (content: string) => {
  return content.replace(/\n/g, '<br>')
}

// 初始化
onMounted(() => {
  const modelStore = useModelConfigStore()
  modelStore.initConfig()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  min-height: calc(100vh - 40px);
}

.page-header {
  margin-bottom: 30px;
}

.header-title {
  margin-top: 16px;
  text-align: center;
}

.header-title h1 {
  color: #dc3545;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  font-size: 28px;
  font-weight: 600;
}

.title-icon {
  font-size: 32px;
}

.subtitle {
  color: #666;
  margin: 12px 0 0 0;
  font-size: 16px;
}

/* 步骤指示器 */
.steps-container {
  margin-top: 30px;
  padding: 0 20px;
}

/* 步骤内容 */
.step-content {
  margin-top: 30px;
}

.step-panel {
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.step-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: none;
  border-radius: 12px;
  min-height: 500px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
  font-size: 16px;
}

.card-header > div:first-child {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-actions {
  display: flex;
  gap: 8px;
}

/* 表单样式 */
.step-form {
  padding: 20px;
}

/* 单选卡片网格 */
.radio-grid {
  display: block;
  width: 100%;
  margin-top: 8px;
}

.radio-grid .el-radio-group {
  display: grid !important;
  grid-template-columns: repeat(5, 1fr);
  gap: 12px;
  width: 100%;
}

.radio-card {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 20px 16px;
  transition: all 0.2s ease;
  cursor: pointer;
  background: #fafbfc;
  margin: 0 !important;
  width: 100%;
  height: 90px;
  display: flex !important;
  align-items: center;
  justify-content: center;
}

.radio-card:hover {
  border-color: #c0c4cc;
  background: #f5f7fa;
}

.radio-card.is-checked {
  border-color: #409eff;
  background: #ecf5ff;
  color: #409eff;
}

.radio-content {
  text-align: center;
  width: 100%;
}

.radio-title {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
  font-size: 15px;
}

.radio-desc {
  color: #909399;
  font-size: 13px;
  line-height: 1.4;
}

.radio-card.is-checked .radio-title {
  color: #409eff;
  font-weight: 600;
}

.radio-card.is-checked .radio-desc {
  color: #337ecc;
}

/* 表单项样式 */
.theme-input,
.content-textarea,
.target-unit-input,
.other-info-textarea {
  margin-top: 8px;
}

.word-count-container {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.word-count-group {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.custom-word-input {
  width: 120px;
}

/* 文件上传 */
.upload-demo {
  width: 100%;
}

/* 生成结果 */
.result-card {
  min-height: 600px;
}

.generate-prompt {
  padding: 80px 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.generating-state {
  padding: 40px;
}

.generating-text {
  text-align: center;
  margin-top: 20px;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.rotating {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.result-content {
  padding: 20px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 16px;
}

.result-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.result-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.generated-text {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 24px;
  line-height: 1.8;
  color: #495057;
  font-size: 14px;
  white-space: pre-wrap;
  word-wrap: break-word;
  min-height: 200px;
}

.generation-info {
  margin-top: 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.stat-value {
  color: #303133;
  font-weight: 600;
  font-size: 14px;
}

/* 操作按钮 */
.step-actions {
  margin-top: 40px;
  display: flex;
  justify-content: center;
  gap: 16px;
  flex-wrap: wrap;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 15px;
  }
  
  .header-title h1 {
    font-size: 24px;
    flex-direction: column;
    gap: 8px;
  }
  
  .radio-grid .el-radio-group {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .word-count-container {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .word-count-group {
    flex-direction: column;
    gap: 8px;
  }
  
  .result-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .step-actions {
    flex-direction: column;
    align-items: center;
  }
  
  .steps-container {
    padding: 0 10px;
  }
}

@media (max-width: 1024px) {
  .radio-grid .el-radio-group {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 480px) {
  .step-form {
    padding: 15px;
  }
  
  .radio-grid .el-radio-group {
    grid-template-columns: 1fr;
  }
  
  .generated-text {
    padding: 16px;
    font-size: 13px;
  }
  
  .result-content {
    padding: 15px;
  }
}
</style>